package com.cbw.dao;

import com.cbw.bean.Book;
import com.cbw.utils.IOUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;

public class BookDao {
    private ArrayList<Book> list = IOUtil.readFromFile();

    public boolean addBook(Book book) {

        if (list.contains(book)) return false;
        list.add(book);
        IOUtil.writeToFile(list);
        return true;
    }

    public boolean removeBook(String bookName) {
        //如果equals方法不是只对bookName的，这么写是无法删除的
        boolean remove = list.remove(new Book(bookName, 0, null));
        IOUtil.writeToFile(list);
        return remove;
    }

    public boolean modify(String bookName, Book newBook) {
        int index = list.indexOf(new Book(bookName, 0, null));
        if (index == -1) return false;
        list.set(index, newBook);
        IOUtil.writeToFile(list);
        return true;
    }

    /**
     * 模糊查询
     *
     * @param keyWord
     * @return
     */
    public ArrayList<Book> queryBooksByName(String keyWord) {
        list = IOUtil.readFromFile();
        ArrayList<Book> temp = new ArrayList<>();

        for (Book book : list) {
            if (book.getBookName().contains(keyWord)) {
                temp.add(book);
            }
        }
        return temp;
    }

    public ArrayList<Book> sortByPublishDate() {
//        Collections.sort(list, new Comparator<Book>() {
//            @Override
//            public int compare(Book o1, Book o2) {
//                return 0;
//            }
//        });
        //
        list = IOUtil.readFromFile();
        list.sort(new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                Date d1 = null;
                Date d2 = null;
                try {
                    d1 = df.parse(o1.getBookPublishDate());
                    d2 = df.parse(o2.getBookPublishDate());

                } catch (ParseException e) {
                }
                return (int) (d1.getTime() - d2.getTime());
            }
        });
        return list;
    }

    public ArrayList<Book> sortByPriceUp() {
        list = IOUtil.readFromFile();
        list.sort(new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return (int) ((o1.getBookPrice() - o2.getBookPrice()) * 100);
            }
        });
        return list;
    }

    public ArrayList<Book> sortByPriceDown() {
        list = IOUtil.readFromFile();
        list.sort(new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return (int) ((o2.getBookPrice() - o1.getBookPrice()) * 100);
            }
        });
        return list;
    }
}